package br.poli.ecomp.sma.massim.action;

import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Atom;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.NumberTermImpl;
import jason.asSyntax.StringTerm;
import jason.asSyntax.StringTermImpl;
import jason.asSyntax.Term;

import java.io.IOException;
import java.io.StringReader;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class FindDirection extends DefaultInternalAction {
	@Override
	public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
		Term x = args[0];
		Term y = args[1];
		Term newX = args[2];
		Term newY = args[3];
		Term direction = args[4];
		// Unfold terms
		double vx = ((NumberTerm)x).solve();
		double vy = ((NumberTerm)y).solve();
		double vNewX = ((NumberTerm)newX).solve();
		double vNewY = ((NumberTerm)newY).solve();
		
		String sDirection = "";
		
		if(vNewX-vx == 1)
		{
			if(vNewY - vy == -1)
			{
				sDirection = "northwest";
			}
			else if(vNewY - vy == 0)
			{
				sDirection = "north";
			}
			else
			{
				sDirection = "northeast";
			}
		}
		else if(vNewX-vx == 0)
		{
			if(vNewY - vy == -1)
			{
				sDirection = "west";
			}
			else if(vNewY - vy == 1)
			{
				sDirection = "lest";
			}
		}
		else
		{
			if(vNewY - vy == -1)
			{
				sDirection = "southwest";
			}
			else if(vNewY - vy == 0)
			{
				sDirection = "south";
			}
			else
			{
				sDirection = "southeast";
			}
		}
		
		un.unifies(direction, new Atom(sDirection));
		// everything ok, so returns true
		return true;
	}
	
	
}
